﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.ERPModels.Production.MasterData;
using ERP.MasterData;
using ERP.MasterData.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace ERP.Web.Controllers.Production.MasterData
{
    // 提供两种路由方式，同时支持 /CustomerManagement 和 /Production/MasterData/CustomerManagement
    [Route("[controller]")]
    [Route("Production/MasterData/[controller]")]
    public class CustomerManagementController : Controller
    {
        private readonly ICustomerManagementService _customerService;
        private readonly IRepository<Customers, int> _customerRepository;
        private readonly Volo.Abp.ObjectMapping.IObjectMapper _objectMapper;

        public CustomerManagementController(
            ICustomerManagementService customerService,
            IRepository<Customers, int> customerRepository,
            Volo.Abp.ObjectMapping.IObjectMapper objectMapper)
        {
            _customerService = customerService;
            _customerRepository = customerRepository;
            _objectMapper = objectMapper;
        }

        [HttpGet]
        [HttpGet("Index")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取客户管理分页列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        [HttpPost("GetList")]
        public async Task<JsonResult> GetList([FromBody] GetCustomerManagementDto dto)
        {
            // 创建查询
            var query = await _customerRepository.GetQueryableAsync();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(dto.CustomerCode))
            {
                query = query.Where(x => x.CustomerCode.Contains(dto.CustomerCode));
            }

            if (!string.IsNullOrWhiteSpace(dto.CustomerName))
            {
                query = query.Where(x => x.CustomerName.Contains(dto.CustomerName));
            }

            if (dto.IsNo.HasValue)
            {
                query = query.Where(x => x.IsNo == dto.IsNo.Value);
            }

            // 获取总记录数
            var totalCount = await query.CountAsync();

            // 应用排序
            query = query.OrderBy(x => x.Id);

            // 应用分页
            int pageSize = dto.PageSize > 0 ? dto.PageSize : 5;
            int pageIndex = dto.PageIndex > 0 ? dto.PageIndex : 1;
            var list = await query.Skip((pageIndex - 1) * pageSize)
                                .Take(pageSize)
                                .ToListAsync();

            // 返回结果
            return Json(new
            {
                code = 0,
                msg = "success",
                count = totalCount,
                data = list
            });
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        [HttpPost("Create")]
        public async Task<IActionResult> Create([FromBody] CustomerManagementDto input)
        {
            try
            {
                var result = await _customerService.CreateAsync(input);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 修改客户
        /// </summary>
        [HttpPost("Update")]
        public async Task<IActionResult> Update([FromBody] CustomerManagementDto input)
        {
            try
            {
                var result = await _customerService.UpdateAsync(input.Id, input);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        [HttpPost("Delete")]
        public async Task<IActionResult> Delete([FromBody] DeleteRequest request)
        {
            try
            {
                await _customerService.DeleteAsync(request.id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        public class DeleteRequest
        {
            public int id { get; set; }
        }

        /// <summary>
        /// 批量删除客户
        /// </summary>
        [HttpPost("BatchDelete")]
        public async Task<IActionResult> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                await _customerService.BatchDeleteAsync(ids);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
}
